package com.iurac.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iurac.domain.Book;
import com.iurac.exception.BorrowException;
import com.iurac.exception.ManageException;
import com.iurac.service.BookService;
import com.iurac.service.impl.BookServiceImpl;
import com.iurac.uitl.SerialNumberUtil;
import com.iurac.uitl.UUIDUtil;
import com.iurac.vo.BorrowVo;
import com.iurac.vo.EchartsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("/book/getBooksByConditionInPage.do")
    @ResponseBody
    public Map<String,Object> getBooksByConditionInPage(@RequestParam(value="page")int page,@RequestParam(value="info") String info,@RequestParam(value="type[]") String[] type,@RequestParam(value="stock") boolean stock) throws IOException {
        List<Book> books = bookService.getBooksByConditionInPage(page*12,info,type,stock);
        Map<String,Object> map = new HashMap<>();
        map.put("count",books.size());
        map.put("books",books);
        return  map;
    }

    @RequestMapping("/book/getBooksById.do")
    @ResponseBody
    public Map<String,Object> getBooksById(@RequestParam(value="id") String id) throws IOException {
        Book book = bookService.getBooksById(id);
        Map<String,Object> map = new HashMap<>();
        if(book!=null){
            map.put("book",book);
            map.put("success",true);
        }else {
            map.put("success",false);
        }

        return map;
    }

    @RequestMapping("/book/getBooksByCondition.do")
    @ResponseBody
    public Map<String,Object> getBooksByCondition(@RequestParam(value="page") int page,@RequestParam("limit") int limit,
                                      @RequestParam(value="title") String title,@RequestParam("press") String press,
                                      @RequestParam(value="author") String author,@RequestParam("minPrice") String minPrice,
                                      @RequestParam(value="maxPrice") String maxPrice,@RequestParam("stock") boolean stock,
                                      @RequestParam(value="type[]") String[] type) throws IOException {
        List<Book> bookList = bookService.getBooksByCondition(title,press,author,minPrice,maxPrice,stock,type);
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",bookList.size());
        map.put("data",bookList);

        return map;
    }

    @RequestMapping("/book/getBooksBySerialNumber.do")
    @ResponseBody
    public Map<String,Object> getBooksBySerialNumber(@RequestParam(value="page") int page,@RequestParam("limit") int limit,
                                      @RequestParam(value="serialNumber") String serialNumber) throws IOException {
        List<Book> bookList = bookService.getBooksBySerialNumber(serialNumber);
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",bookList.size());
        map.put("data",bookList);

        return map;
    }

    @RequestMapping("/book/getBookTypeCharts.do")
    @ResponseBody
    public EchartsVo getBookTypeCharts() throws IOException {
        EchartsVo echartsVo = bookService.getBookTypeCharts();
        return  echartsVo;
    }

    @RequestMapping("/book/getDateAboutBook.do")
    @ResponseBody
    public Map<String, Object> getDateAboutBook() throws IOException {
        Map<String, Object> map = bookService.getDateAboutBook();
        return  map;
    }

    @RequestMapping("/book/deleteBookById.do")
    @ResponseBody
    public Map<String, Object> deleteBookById(@RequestParam(value="id") String id) throws IOException {
        deleteImageByBid(id);
        boolean success;
        String msg = "";
        try {
            success = bookService.deleteBookById(id);
        } catch (ManageException e) {
            e.printStackTrace();
            success = false;
            msg = e.getMessage();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success",success);
        map.put("msg",msg);

        return  map;
    }

    @RequestMapping("/book/saveBook.do")
    @ResponseBody
    public Map<String, Object> saveBook(@RequestParam(value="imgFile",required = false) MultipartFile file, Book book) throws IOException {
        if(!file.isEmpty()){
            String originalFileName = file.getOriginalFilename();
            String fileName = book.getTitle()+originalFileName.substring(originalFileName.lastIndexOf("."));
            String uuid = UUIDUtil.getUUID();
            String newFileName = uuid+fileName;
            File target = new File("D:\\upload",newFileName);
            try {
                file.transferTo(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
            book.setImg(newFileName);
        }else {
            book.setImg("404.jpg");
        }
        book.setId(UUIDUtil.getUUID());
        book.setSerialNumber(SerialNumberUtil.getNumber(book.getLocation()));
        book.setBorrows("0");
        boolean success;
        String msg = "";
        try {
            success = bookService.saveBook(book);
        } catch (ManageException e) {
            e.printStackTrace();
            success = false;
            msg = e.getMessage();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success",success);
        map.put("msg",msg);

        return map;
    }

    @RequestMapping("/book/updateBook.do")
    @ResponseBody
    public Map<String, Object> updateBook(@RequestParam(value="imgFile",required = false) MultipartFile file, Book book) throws IOException {
        if(!file.isEmpty()){
            deleteImageByBid(book.getId());
            String originalFileName = file.getOriginalFilename();
            String fileName = book.getTitle()+originalFileName.substring(originalFileName.lastIndexOf("."));
            String uuid = UUIDUtil.getUUID();
            String newFileName = uuid+fileName;
            File target = new File("D:\\upload",newFileName);
            try {
                file.transferTo(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
            book.setImg(newFileName);
        }
        book.setSerialNumber(SerialNumberUtil.getNumber(book.getLocation()));
        boolean success;
        String msg = "";
        try {
            success = bookService.updateBook(book);
        } catch (ManageException e) {
            e.printStackTrace();
            success = false;
            msg = e.getMessage();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success",success);
        map.put("msg",msg);

        return  map;
    }

    private void deleteImageByBid(String id){
        Book book = bookService.getBooksById(id);
        if(!book.getImg().equals("404.jpg")){
            File folder = new File("D:\\upload");
            File[] files = folder.listFiles();
            for(File file : files){
                if (file.getName().equals(book.getImg())) {
                    System.out.println("删除"+file.getName()+"图片");
                    boolean delete = file.delete();
                }
            }
        }
    }
}
